#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/uio.h>
#include <string.h>
#include <fcntl.h>
#define BUF_SIZE 10


#define HOST "localhost"
#define USERNAME "root"
#define PASSWORD ""
#define DATABASE "tcmu"

struct file_state {
	int fd;
};

void printResult(MYSQL *mysqlPrint);

int main()
{
    struct file_state *state = calloc(1, sizeof(*state));;
    char *path = "/root/shunzi/elvis-test";
    // Open the file with path.(With mode)
	state->fd = open(path, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
    printf("Read file with state fd : %d\n", state->fd);
    struct iovec read_file_iv[2];
    read_file_iv[0].iov_base = calloc(20, sizeof(char));
    read_file_iv[0].iov_len = 10;
    read_file_iv[1].iov_base = calloc(20, sizeof(char));
    read_file_iv[1].iov_len = 20;
    struct iovec read_db_iv[2];
    /**
     * 在用readv读写文件时，缓冲区先手动提前设置iov_len长度，需要告知系统调用读取多长的数据
     * 才能进行相应的读写操作，根据长度决定读写的数据长度。如上例所示，对应的输出结果将为
     * Read result ret is 14. Hello! World!
     * Read result iov[0] is Hello! Wor.
     * Read result iov[1] is ld! .
     **/ 
    int read_ret = readv(state->fd, read_file_iv, 2);
    printf("Read result ret is %d.\n", read_ret);
    printf("Read result iov[0] is %s.\n", (char *) read_file_iv[0].iov_base);
    printf("Read result iov[1] is %s.\n", (char *) read_file_iv[1].iov_base);

    MYSQL connection;
    mysql_init(&connection);
    mysql_real_connect(&connection, HOST, USERNAME, PASSWORD, DATABASE, 0, NULL, 0);
    mysql_query(&connection, "set names 'utf8'");
    printf("Start to query the data to Mysql.\n");
    char *select_sql_caluse = "SELECT `Value` FROM kv WHERE `Key` = ";
    int i = 0;
    for (i = 0; i < 2; i++)
    {
        char *key = (char *) calloc(5, sizeof(char));
        sprintf(key, "%s%d", "key", i);
        char *sql = (char *) calloc(200, sizeof(char));
        sprintf(sql, "%s'%s'", select_sql_caluse, key);
        printf("Prepare to query！\n");
        printf("Select sql is %s.\n", sql);
        int query_result = mysql_query(&connection, sql);
        if (query_result)
        {
            printf("Error happend in query！\n");
            break;
        }
        MYSQL_RES *result = mysql_store_result(&connection);
        MYSQL_ROW row = mysql_fetch_row(result);
        read_db_iv[i].iov_base = calloc(1, BUF_SIZE);
        read_db_iv[i].iov_base = row[0];
        read_db_iv[i].iov_len = strlen(row[0]);
        printf("Read result from DB iov[%d] is %s.\n", i, (char *) read_db_iv[i].iov_base);
    }		
    mysql_close(&connection);
    return 0;
}
